﻿#ifndef __SS_MALLOC_H__
#define __SS_MALLOC_H__
#include "ssDefaultMalloc.h"
#include "./ssDoublyList.h"
#include "../thread/threadLock/ssAtomicLock.h"

namespace StarSeeker
{

template<ulint MEMSIZE>
class ssMalloc : public ssIMalloc
{
public:
	ssMalloc()
	{
	}
	~ssMalloc()
	{
		Clear();
	}
	//分配
	void* Malloc()
	{
		return m_list.Allot();
	}
	//回收
	bool Free(void* pt)
	{
		m_list.Erase(pt);
		return true;
	}
	//回收所有分配的内存
	void Recovery()
	{
		m_list.Empty();
	}
	//释放没有使用的内存
	void Release()
	{
		m_list.ReleaseFreeNode();
	}
	//内存是否属于池
	bool IsFrom(void* pt)
	{
		return m_list.DataIsFrom(pt);
	}
	//分配的数量
	ulint Count()
	{
		return m_list.UsedCount();
	}
	//释放所有内存
	void Clear()
	{
		m_list.Clear();
	}
private:
	ssMalloc(const ssMalloc& mc) {}
	void operator= (const ssMalloc& mc) {}
private:
	ssDoublyList<MEMSIZE>		m_list;
};

template<ulint MEMSIZE>
class ssMutexMalloc : public ssIMalloc
{
public:
	ssMutexMalloc()
	{
	}
	~ssMutexMalloc()
	{
		Clear();
	}
	//分配对象
	void* Malloc()
	{
		void* tmp = 0;
		m_lock.Lock();
		tmp = m_list.Allot();
		m_lock.Unlock();
		return tmp;
	}
	//回收对象
	void Free(void* pt)
	{
		m_lock.Lock();
		m_list.Erase(pt);
		m_lock.Unlock();
	}
	//回收所有分配的内存
	void Recovery()
	{
		m_lock.Lock();
		m_list.Empty();
		m_lock.Unlock();
	}
	//释放没有使用的内存
	void Release()
	{
		m_lock.Lock();
		m_list.ReleaseFreeNode();
		m_lock.Unlock();
	}
	//内存是否属于池
	bool IsFrom(void* pt)
	{
		return m_list.DataIsFrom(pt);
	}
	//分配的数量
	ulint Count()
	{
		return m_list.UsedCount();
	}
	//释放所有内存
	void Clear()
	{
		m_lock.Lock();
		m_list.Clear();
		m_lock.Unlock();
	}
private:
	ssMutexMalloc(const ssMutexMalloc& mc) {}
	void operator= (const ssMutexMalloc& mc) {}
private:
	ssDoublyList<MEMSIZE>	m_list;
	ssAtomicLock			m_lock;
};

}
#endif
